package com.huobao.yunying.fragments;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.easemob.chat.EMMessage;
import com.easemob.easeui.ui.EaseChatFragment;
import com.easemob.easeui.widget.chatrow.EaseChatRow;
import com.easemob.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.huobao.yunying.entity.UserInfo;
import com.huobao.yunying.huanxin.ui.DemoHelper;
import com.huobao.yunying.huanxin.ui.chatrow.ChatRowEvaluation;
import com.huobao.yunying.huanxin.ui.chatrow.ChatRowPictureText;
import com.huobao.yunying.huanxin.ui.chatrow.ChatRowRobotMenu;
import com.huobao.yunying.huanxin.ui.chatrow.ChatRowTransferToKefu;
import com.huobao.yunying.utils.UserInfoUtils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2016/9/8.
 */
public class ChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentListener {
	// 避免和基类定义的常量可能发生的冲突，常量从11开始定义
	private static final int ITEM_FILE = 11;
	private static final int ITEM_SHORT_CUT_MESSAGE = 12;
	public static final int REQUEST_CODE_CONTEXT_MENU = 14;

	private static final int MESSAGE_TYPE_SENT_PICTURE_TXT = 1;
	private static final int MESSAGE_TYPE_RECV_PICTURE_TXT = 2;
	private static final int MESSAGE_TYPE_SENT_ROBOT_MENU = 3;
	private static final int MESSAGE_TYPE_RECV_ROBOT_MENU = 4;

	// evaluation
	private static final int MESSAGE_TYPE_SENT_EVAL = 5;
	private static final int MESSAGE_TYPE_RECV_EVAL = 6;

	// transfer to kefu message
	private static final int MESSAGE_TYPE_SENT_TRANSFER_TO_KEFU = 7;
	private static final int MESSAGE_TYPE_RECV_TRANSFER_TO_KEFU = 8;


	private static final int REQUEST_CODE_SELECT_FILE = 11;
	//EVALUATION
	public static final int REQUEST_CODE_EVAL = 26;
	//SHORT CUT MESSAGES
	public static final int REQUEST_CODE_SHORTCUT = 27;
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		messageList.setShowUserNick(true);
		setChatFragmentListener(this);
	}

	@Override
	protected void setUpView() {
		setChatFragmentListener(this);
		super.setUpView();
	}

	@Override
	protected void registerExtendMenuItem() {
		super.registerExtendMenuItem();
	}

	/**
	 * 技能组（客服分组）发消息发到某个组
	 *
	 * @param message   消息
	 * @param groupName 分组名称
	 */
	private void pointToSkillGroup(EMMessage message, String groupName) {
		try {
			JSONObject weichatJson = getWeichatJSONObject(message);
			weichatJson.put("queueName", groupName);
			message.setAttribute("weichat", weichatJson);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取消息中的扩展 weichat是否存在并返回jsonObject
	 *
	 * @param message
	 * @return
	 */
	private JSONObject getWeichatJSONObject(EMMessage message) {
		JSONObject weichatJson = null;
		try {
			String weichatString = message.getStringAttribute("weichat", null);
			if (weichatString == null) {
				weichatJson = new JSONObject();
			} else {
				weichatJson = new JSONObject(weichatString);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return weichatJson;
	}

	/**
	 * 设置消息扩展属性
	 *
	 * @param message
	 */
	@Override
	public void onSetMessageAttributes(EMMessage message) {
		showPhoto(message);
		setUserInfoAttribute(message);
		pointToSkillGroup(message, "shouqian");
		showZhuanjie(message);
		Toast.makeText(getActivity(), "shezhi wanbi", Toast.LENGTH_SHORT).show();
	}

	/**
	 * 设置用户的属性，
	 * 通过消息的扩展，传递客服系统用户的属性信息
	 *
	 * @param message
	 */
	private void setUserInfoAttribute(EMMessage message) {
		JSONObject weichatJson = getWeichatJSONObject(message);
		try {
			UserInfo info = UserInfoUtils.getUserInfo(getActivity());
			JSONObject visitorJson = new JSONObject();
			visitorJson.put("userNickname", TextUtils.isEmpty(info.nikename) ? info.user_name : info.nikename);
			visitorJson.put("phone", info.user_name);
			weichatJson.put("visitor", visitorJson);

			message.setAttribute("weichat", weichatJson);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void showPhoto(EMMessage message) {
		JSONObject weichatJson = getWeichatJSONObject(message);
		try {
			UserInfo info = UserInfoUtils.getUserInfo(getActivity());
			JSONObject visitorJson = new JSONObject();
			visitorJson.put("userNickname", TextUtils.isEmpty(info.nikename) ? info.user_name : info.nikename);
			visitorJson.put("avatar", info.portrait);
			weichatJson.put("agent", visitorJson);

			message.setAttribute("weichat", weichatJson);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void showZhuanjie(EMMessage message) {
		JSONObject weichatJson = getWeichatJSONObject(message);
		try {
			JSONObject visitorJson = new JSONObject();
			visitorJson.put("eventName", "ServiceSessionTransferedEvent");
			visitorJson.put("eventObj", null);
			weichatJson.put("event", visitorJson);

			message.setAttribute("weichat", weichatJson);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 进入会话详情
	 */
	@Override
	public void onEnterToChatDetails() {

	}

	/**
	 * 用户头像点击事件
	 *
	 * @param username
	 */
	@Override
	public void onAvatarClick(String username) {

	}

	/**
	 * 消息气泡框点击事件
	 *
	 * @param message
	 */
	@Override
	public boolean onMessageBubbleClick(EMMessage message) {
		return false;
	}

	/**
	 * 消息气泡框长按事件
	 *
	 * @param message
	 */
	@Override
	public void onMessageBubbleLongClick(EMMessage message) {

	}

	/**
	 * 扩展输入栏item点击事件,如果要覆盖EaseChatFragment已有的点击事件，return true
	 *
	 * @param itemId
	 * @param view
	 * @return
	 */
	@Override
	public boolean onExtendMenuItemClick(int itemId, View view) {
		return false;
	}

	/**
	 * 设置自定义chatrow提供者
	 *
	 * @return
	 */
	@Override
	public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
		return new CustomChatRowProvider();
	}


	/**
	 * chat row provider
	 *
	 */
	private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
		@Override
		public int getCustomChatRowTypeCount() {
			//此处返回的数目为getCustomChatRowType 中的布局的个数
			return 8;
		}

		@Override
		public int getCustomChatRowType(EMMessage message) {
			if (message.getType() == EMMessage.Type.TXT) {
				if (DemoHelper.getInstance().isRobotMenuMessage(message)) {
					// 机器人 列表菜单
					return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_ROBOT_MENU
							: MESSAGE_TYPE_SENT_ROBOT_MENU;
				} else if (DemoHelper.getInstance().isEvalMessage(message)) {
					// 满意度评价
					return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_EVAL : MESSAGE_TYPE_SENT_EVAL;
				} else if (DemoHelper.getInstance().isPictureTxtMessage(message)) {
					// 订单图文组合
					return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_PICTURE_TXT
							: MESSAGE_TYPE_SENT_PICTURE_TXT;
				} else if(DemoHelper.getInstance().isTransferToKefuMsg(message)){
					//转人工消息
					return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TRANSFER_TO_KEFU
							: MESSAGE_TYPE_SENT_TRANSFER_TO_KEFU;
				}
			}
			return 0;
		}

		@Override
		public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
			if (message.getType() == EMMessage.Type.TXT) {
				if (DemoHelper.getInstance().isRobotMenuMessage(message)) {
					return new ChatRowRobotMenu(getActivity(), message, position, adapter);
				} else if (DemoHelper.getInstance().isEvalMessage(message)) {
					return new ChatRowEvaluation(getActivity(), message, position, adapter);
				} else if (DemoHelper.getInstance().isPictureTxtMessage(message)) {
					return new ChatRowPictureText(getActivity(), message, position, adapter);
				}else if (DemoHelper.getInstance().isTransferToKefuMsg(message)){
					return new ChatRowTransferToKefu(getActivity(), message, position, adapter);
				}
			}
			return null;
		}
	}

	public void sendRobotMessage(String content, String menuId) {
		EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
		if (!TextUtils.isEmpty(menuId)) {
			JSONObject msgTypeJson = new JSONObject();
			try {
				JSONObject choiceJson = new JSONObject();
				choiceJson.put("menuid", menuId);
				msgTypeJson.put("choice", choiceJson);
			} catch (Exception e) {
			}
			message.setAttribute("msgtype", msgTypeJson);
		}
		sendMessage(message);
	}

}
